<?php

namespace app\adminapi\controller;

use app\helpers\Common;

use think\facade\Db;
use think\Exception;
use think\Request;

class Article extends Base
{
    public function initialize()
    {
        parent::initialize();

        $this->modelName = 'Article';
        $this->defaultOrder = 'sorting ASC, created_at DESC';
    }

    /**
     * Save
     */
    public function save(Request $request)
    {
        Db::startTrans();
        try {
            $className = '\\app\\' . $this->appName . '\\model\\' . $this->modelName;
            $model = new $className;

            $data = $this->evalData($request);
            $images = $data['images'];
            $files = $data['files'];
            unset($data['images'], $data['files']);
            if (isset($data['id']) && $data['id']) {
                $info = $model->where('id', $data['id'])->field('id')->find();
                if (!$info) {
                    return api_response(self::STATUS_ERROR, '不存在', '');
                }
                $data['updated_at'] = time();
                $message = '保存失败';
                $result = $model->where(['id' => $data['id']])->update($data);

                $afterAction = '_after_update';
            } else {
                $data['created_at'] = time();
                $message = '创建失败';
                $result = $model->create($data);
                $data['id'] = $result->id ?? 0;

                $afterAction = '_after_insert';
            }
            if ($result === false) {
                return api_response(self::STATUS_ERROR, $message, []);
            }

            $data['images'] = $images;
            $data['files'] = $files;
            // Query执行后的操作
            $model->$afterAction($data);
            if (isset($info)) {
                $afterRes = $this->afterUpdate($data, $info);
            } else {
                $afterRes = $this->afterInsert($data);
            }
            if ($afterRes['code'] != 1) {
                return api_response(self::STATUS_ERROR, $afterRes['msg'] ?? 'after error', []);
            }

            Db::commit();
            return api_response(self::STATUS_SUCCESS, self::MSG_SUCCESS, $data);
        } catch (Exception $e) {
            Db::rollback();
            return api_response(self::STATUS_ERROR, '失败', $e->getMessage());
        }
    }

    /**
     * 分类
     */
    public function cateList(Request $request)
    {
        $param = $request->param();

        $className = '\\app\\' . $this->appName . '\\model\\' . 'ArticleCate';
        $model = new $className;
        $field = '*';
        $where = [
            ['status', '=', 1]
        ];
        $order = 'sorting ASC, created_at DESC';
        $list = $model->where($where)->field($field)->order($order)->select()->toArray();
        if ($list) {
            $list = $model->formatDatas($list);
            $list = list_to_tree($list, 'id', 'parent_id', 'children', 0);
        }
        $data = [
            'data' => $list
        ];

        return api_response(self::STATUS_SUCCESS, '', $data);
    }

    /**
     * Eval data for post data save
     *
     * @param Request $request
     * @return array
     */
    protected function evalData($request)
    {
        $param = $request->param();

        $data = [
            'id' => $param['id'],
            'cate_id' => $param['cate_id'],
            'name' => $param['name'],
            'cover_img' => $param['cover_img'],
            'source' => $param['source'],
            'keywords' => $param['keywords'],
            'description' => $param['description'],
            'content' => $param['content'],
            'post_time' => $param['post_time'],
            'is_show' => $param['is_show'],
            'is_top' => $param['is_top'],
            'is_recommend' => $param['is_recommend'],
            'is_comment' => $param['is_comment'],
            'sorting' => $param['sorting'],
            'status' => $param['status'],
        ];
        $data['post_time'] = strtotime($data['post_time']);
        $images = [];
        if (isset($param['images']) && $param['images']) {
            foreach ($param['images'] as $image) {
                $images[] = $image['filepath'];
            }
        }
        $data['images'] = $images;
        // 附件
        $files = [];
        if (isset($param['files']) && $param['files']) {
            foreach ($param['files'] as $file) {
                $files[] = $file['filepath'];
            }
        }
        $data['files'] = $files;

        return $data;
    }

    /**
     * 处理列表数据
     */
    protected function handleListData($data)
    {
        $className = '\\app\\' . $this->appName . '\\model\\' . $this->modelName;
        $model = new $className;

        $data = $model->formatDatas($data, ['format_source' => 'backend']);

        return $data;
    }
}
